package com.cynteka.cyfoman.ui.bind;

import com.cynteka.cyfoman.core.ValueObject;
import com.cynteka.cyfoman.core.config.ValueObjectListener;

import javax.swing.text.JTextComponent;
import java.awt.*;
import java.util.Map;

/**
 * User: Sergey
 * Date: 10.08.11
 * Time: 19:00
 */
public class TextFieldBinder implements ComponentBeanBinder {

    @Override
    public boolean bind(final ValueObject bean, Object component, final String propertyName) {
        if(component instanceof JTextComponent) {
            final JTextComponent textComponent = (JTextComponent) component;
            ValueObjectListener listener = new ValueObjectListener() {
                @Override
                public void changed(ValueObject sender) {
                    Object o = bean.get(propertyName);
                    String s = String.valueOf(o == null ? "" : o);
                    textComponent.setText(s);
                }

                @Override
                public void prepareToBeStored(ValueObject valueObject) {
                    String s = textComponent.getText();
                    bean.setParam(propertyName, s);
                    bean.removeListener(this);
                }
            };
            bean.addListener(listener);
            listener.changed(bean);
            return true;
        }
        return false;
    }
}
